package cn.aishua.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.json.JSONObject;

import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.aishua.MyApplication;
import cn.aishua.R;
import cn.aishua.data.DatabaseOperator;
import cn.aishua.data.ResourceDataParser;
import cn.aishua.data.ResourceDataParser.Item;
import cn.aishua.location.Locator;
import cn.aishua.location.Locator.Callback;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.main.FindActivity;
import cn.aishua.ui.main.HotsActivity;
import cn.aishua.ui.main.VendorListActivity;
import cn.aishua.ui.myKaka.LoginActivity;
import cn.aishua.ui.myKaka.MemberCenterActivity;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.ui.setting.SettingActivity;
import cn.aishua.ui.vendor.HaveAShakeActivity;
import cn.aishua.util.Constant;
import cn.aishua.util.SharedPrefConst;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.BMapManager;

@SuppressWarnings( "deprecation" )
public class MainActivityGroup
    extends ActivityGroup
    implements OnTouchListener, OnGestureListener
{
    public static String TAG_HOME_PAGE = "homePage";
    public static String TAG_VENDOR = "vendor";

    public static String TAG_SETTING = "setting";
    public static String TAG_ASSIST_FUNCTION = "assistFunction";
    public static String TAB = "tab";

    // pages which have tab indicator
    public static String TAG_USER_INFO = "TAG_USER_INFO";
    public static String TAG_SHAKE = "TAG_SHAKE";
    public static String TAG_HOT = "TAG_HOT";
    public static String TAG_FIND = "TAG_FIND";

    // pages which don't have tab indicator
    public static String TAG_REG = "TAG_REG";
    public static String TAG_REG_NEXT = "TAG_REG_NEXT";
    public static String TAG_MY_CARDS = "TAG_MY_CARDS";
    public static String TAG_SEARCH_BOX_RESULT = "TAG_SEARCH_BOX_RESULT";

    //    public FrameLayout tabContent;

    protected int widthOfNaviBar; //width of menu
    protected int p1 = 0; // x position of touch down
    protected int p2 = 0; // x position of current
    protected int d = 0; // x distance between p1 and p2

    public boolean isNaviBarShown = false;

    private List<Integer> cateIdList = new ArrayList<Integer>();

    //    private TabHost tabHost;

    private AutoCompleteTextView actvSearch;
    private ImageView ivClean;
    private Button btnSetting;

    public boolean ignoreNaviBar = true;

    public FrameLayout clickArea;

    private ListView lvTabs;
    private GridView gvTabs;
    public LinearLayout llLogin;

    FixTabAdapter fixAdapter;
    DynamicTabAdapter dynAdapter;

    private LinearLayout llContainer;

    private SharedPreferences sharedPref;

    public boolean needsOwnBack = false; // indicator for sub activity whether needs to perform own onBackPressed

    private static int SLIDE_SPEED = 20;

    private GestureDetector mGestureDetector;// 手势  
    private boolean isScrolling = false;
    private float mScrollX; // 滑块滑动距离  

    private boolean isItemClickable = true; // avoid click item several times in a short time

    //    private View selectedItem;

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        Log.d( "MainActivity", "onCreate( Bundle savedInstanceState )" );
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_group );
        retieveLocation();
        initiate();
    }

    @Override
    protected void onNewIntent( Intent intent )
    {
        // get current tab
        String tab = intent.getStringExtra( TAB );
        Log.d( "MainActivity", "tag: " + tab );
        if( MainActivityGroup.TAG_USER_INFO.equals( tab ) )
        {
            ignoreNaviBar = true;
            updateUserInfo();
            llLogin.performClick();
        }
    }

    private void retieveLocation()
    {
        Locator locator = Locator.getInstance( this );
        if( locator.getLocation() == null )
        {
            final ProgressDialog dialog = new ProgressDialog( this );
            dialog.setTitle( "获取用户位置信息" );
            dialog.setMessage( "定位中" );
            dialog.setButton( "取消", new DialogInterface.OnClickListener()
            {

                public void onClick( DialogInterface dialog, int which )
                {
                    dialog.dismiss();
                }
            } );
            dialog.show();

            locator.find( new Callback()
            {
                @Override
                public void onFindFinished( BDLocation location )
                {
                    if( dialog.isShowing() )
                    {
                        dialog.dismiss();
                    }
                }
            } );
        }
    }

    private void initiate()
    {
        SplashActivity.MAIN_IS_IN_STACK = true;

        sharedPref = getSharedPreferences( "userInfo", Context.MODE_PRIVATE );

        clickArea = (FrameLayout) findViewById( R.id.clickArea );
        clickArea.setOnTouchListener( this );

        llContainer = (LinearLayout) findViewById( R.id.main_group_container );
        //        llContainer.setOnTouchListener( this );

        mGestureDetector = new GestureDetector( this );
        mGestureDetector.setIsLongpressEnabled( false );

        btnSetting = (Button) findViewById( R.id.main_group_btn_setting );

        initiateSearchBox();

        llLogin = (LinearLayout) findViewById( R.id.navi_tab_ll_login );

        // fix tabs
        lvTabs = (ListView) findViewById( R.id.main_group_fix_tabs );
        fixAdapter = new FixTabAdapter( generateFixTabs() );
        lvTabs.setAdapter( fixAdapter );

        // dynamic tabs
        gvTabs = (GridView) findViewById( R.id.main_group_tabs );
        widthOfNaviBar = gvTabs.getLayoutParams().width;
        dynAdapter = new DynamicTabAdapter( generateDynamicTabs() );
        gvTabs.setAdapter( dynAdapter );

        lvTabs.setOnItemClickListener( new OnItemClickListener()
        {

            @Override
            public void onItemClick( AdapterView<?> parent, View view, int position, long id )
            {
                if( isItemClickable )
                {
                    isItemClickable = false;
                    switchActivityForFixTabs( position );
                }

            }
        } );

        gvTabs.setOnItemClickListener( new OnItemClickListener()
        {

            @Override
            public void onItemClick( AdapterView<?> parent, View view, int position, long id )
            {
                if( isItemClickable )
                {
                    isItemClickable = false;
                    switchActivityForDynTabs( position );
                }

            }

        } );

        switchActivityForFixTabs( 0 );
        enableNaviBar( false );
        updateUserInfo();

        // handle automatic login
        handleAutoLogin();
    }

    class OnClickToLoginPage
        implements OnClickListener
    {

        @Override
        public void onClick( View v )
        {
            if( isItemClickable )
            {
                isItemClickable = false;
                dynAdapter.select( -1 );
                fixAdapter.select( -1 );
                llContainer.removeAllViews();

                Editor editor = sharedPref.edit();
                editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, true );
                editor.commit();

                Intent intent = new Intent( MainActivityGroup.this, LoginActivity.class );
                Window subActivity = getLocalActivityManager().startActivity( "subActivity", intent );
                //容器添加View  
                llContainer.addView( subActivity.getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT );

                isHomePage = false;

                handleNaviBar();
            }
        }
    }

    class OnClickToMemberCenterPage
        implements OnClickListener
    {

        @Override
        public void onClick( View v )
        {
            if( isItemClickable || !isNaviBarShown )
            {
                if( !isNaviBarShown )
                {
                    isItemClickable = true;
                }
                else
                {
                    isItemClickable = false;
                }
                dynAdapter.select( -1 );
                fixAdapter.select( -1 );
                llContainer.removeAllViews();

                Intent intent = new Intent( MainActivityGroup.this, MemberCenterActivity.class );
                intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
                Window subActivity = getLocalActivityManager().startActivity( "subActivity", intent );
                //容器添加View  
                llContainer.addView( subActivity.getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT );

                isHomePage = false;

                handleNaviBar();
            }
        }
    }

    public void switchActivityForFixTabs( int id )
    {
        dynAdapter.select( -1 ); // cancel select of dynamic tabs
        fixAdapter.select( id );

        llContainer.removeAllViews();//必须先清除容器中所有的View  
        Intent intent = null;

        String activityId = "subActivity";

        switch( id )
        {
            case 0:
                intent = new Intent( this, HotsActivity.class );
                intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP |  Intent.FLAG_ACTIVITY_SINGLE_TOP );
                intent.putExtra( "isPoster", false );
                isHomePage = true;
                activityId = "hotsActivity";
                break;
            case 1:
                intent = new Intent( this, HotsActivity.class );
                intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP |  Intent.FLAG_ACTIVITY_SINGLE_TOP );
                intent.putExtra( "isPoster", true );
                activityId = "hotsActivity";
                isHomePage = false;
                break;
            case 2:
                intent = new Intent( this, FindActivity.class );
                isHomePage = false;
                break;
            case 3:
                intent = new Intent( this, HaveAShakeActivity.class );
                isHomePage = false;
                break;
            case 4:
                intent = newVendorListIntent( 0, 0 );
                intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
                isHomePage = false;
                break;
            default:
                break;
        }
        //Activity 转为 View  
        Window subActivity = getLocalActivityManager().startActivity( activityId, intent );
        //容器添加View  
        llContainer.addView( subActivity.getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT );

        handleNaviBar();
    }

    public void switchActivityForDynTabs( int id )
    {
        fixAdapter.select( -1 ); // cancel select of fix tabs
        dynAdapter.select( id );
        llContainer.removeAllViews();//必须先清除容器中所有的View  
        Intent intent = null;

        int cateId = cateIdList.get( id );
        intent = newVendorListIntent( cateId, 0 );
        intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
        //Activity 转为 View  
        Window subActivity = getLocalActivityManager().startActivity( "subActivity", intent );
        //容器添加View  
        llContainer.addView( subActivity.getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT );

        isHomePage = false;

        handleNaviBar();
    }

    private void handleAutoLogin()
    {

        if( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_CHECKED, false )
            && sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_LOGIN_IS_NOT_DONE, true )
            && !sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false ) )
        {

            String mobileNumber = sharedPref.getString( SharedPrefConst.SHARED_PREF_STR_USER_NAME, "" );
            String pwd = sharedPref.getString( SharedPrefConst.SHARED_PREF_STR_PWD, "" );

            new DataExchangeAsyncTask( this, "自动登陆" )
            {

                @Override
                protected HttpResponse sendRequest( String... params )
                {
                    return HttpRequestUtil.getInstance().login( params );
                }

                @Override
                protected void handleSuccResponse( String strJson )
                {
                    if( strJson.contains( "error" ) )
                    {
                        return;
                    }

                    Editor editor = sharedPref.edit();
                    editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN, true );
                    editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false );
                    editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_LOGIN_IS_NOT_DONE, false );
                    editor.commit();

                    new DataExchangeAsyncTask( MainActivityGroup.this, "获取用户信息" )
                    {

                        @Override
                        protected HttpResponse sendRequest( String... params )
                        {
                            return HttpRequestUtil.getInstance().getUserinfo();
                        }

                        @Override
                        protected void handleSuccResponse( String strJson ) throws Exception
                        {
                            MemberCenterActivity.JSON_RES = strJson;

                            JSONObject jsonResult = new JSONObject( strJson );
                            JSONObject jsonObj = jsonResult.getJSONObject( "user" );
                            String userName = jsonObj.getString( "account_name" );
                            int credit = jsonObj.getInt( "usable_credit" );
                            String mobileNumber = jsonObj.getString( "mobile" );

                            Editor editor = sharedPref.edit();
                            editor.putString( MemberCenterActivity.SHARED_PREF_STR_MOBILE_NUMBER, mobileNumber );
                            editor.putString( MemberCenterActivity.SHARED_PREF_STR_ACCOUNT_NAME, userName );
                            editor.putString( MemberCenterActivity.SHARED_PREF_STR_USER_CREDIT, "" + credit );
                            editor.commit();

                            updateUserInfo();
                        }
                    }.execute();
                }
            }.execute( mobileNumber, pwd );
        }
    }

    private void initiateSearchBox()
    {
        ivClean = (ImageView) findViewById( R.id.serach_box_iv_clean );

        actvSearch = (AutoCompleteTextView) findViewById( R.id.search_box );

        // initiate clean button at the end of this search box
        actvSearch.addTextChangedListener( new TextWatcher()
        {

            public void onTextChanged( CharSequence s, int start, int before, int count )
            {

            }

            public void beforeTextChanged( CharSequence s, int start, int count, int after )
            {

            }

            public void afterTextChanged( Editable s )
            {
                if( "".equals( s.toString() ) )
                {
                    ivClean.setVisibility( View.INVISIBLE );
                }
                else
                {
                    ivClean.setVisibility( View.VISIBLE );
                }
            }
        } );

        actvSearch.setOnClickListener( new OnClickListener()
        {

            public void onClick( View v )
            {
                actvSearch.showDropDown();
            }
        } );

        actvSearch.setOnKeyListener( new OnKeyListener()
        {
            @Override
            public boolean onKey( View v, int keyCode, KeyEvent event )
            {
                String text = ( (TextView) v ).getText().toString();

                if( keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP )
                {
                    handleNaviBar();
                    Intent intent = new Intent( MainActivityGroup.this, VendorListActivity.class );
                    intent.putExtra( Constant.EXTRA_STR_CRITERIA_NAME, text );
                    intent.putExtra( Constant.EXTRA_BOOL_IS_SEARCH, true );
                    startActivity( intent );

                    if( DatabaseOperator.getInstance().insertHistory( text ) )
                    {
                        setAdapter();
                    }
                }
                return true;
            }
        } );
        // press Enter to search
        //        actvSearch.setOnEditorActionListener( new OnEditorActionListener()
        //        {
        //
        //            public boolean onEditorAction( TextView view, int actionId, KeyEvent event )
        //            {
        //                String text = ( (TextView) view ).getText().toString();
        //
        //                if( actionId == EditorInfo.IME_ACTION_SEARCH )
        //                {
        //                    handleNaviBar();
        //                    Intent intent = new Intent( MainActivityGroup.this, VendorListActivity.class );
        //                    intent.putExtra( Constant.EXTRA_STR_CRITERIA_NAME, text );
        //                    intent.putExtra( Constant.EXTRA_BOOL_IS_SEARCH, true );
        //                    startActivity( intent );
        //
        //                    if( DatabaseOperator.getInstance().insertHistory( text ) )
        //                    {
        //                        setAdapter();
        //                    }
        //                }
        //                return true;
        //
        //            }
        //        } );

        actvSearch.setOnItemSelectedListener( new OnItemSelectedListener()
        {

            public void onItemSelected( AdapterView<?> parent, View view, int position, long id )
            {
                String text = ( (TextView) view ).getText().toString();
                actvSearch.setText( text );
                //                Intent intent = new Intent( getApplicationContext(), FindResultActivity.class );
                //                intent.putExtra( EXTRA_STR_VENDOR_NAME, text );
                //                startActivity( intent );
                if( DatabaseOperator.getInstance().insertHistory( text ) )
                {
                    setAdapter();
                }
            }

            public void onNothingSelected( AdapterView<?> parent )
            {

            }
        } );

        // get 5 recent records
        setAdapter();
    }

    private void setAdapter()
    {
        List<String> list = DatabaseOperator.getInstance().getRecent5History();
        //自动提示
        ArrayAdapter<String> adapt = new ArrayAdapter<String>( this, android.R.layout.simple_dropdown_item_1line, list );
        actvSearch.setAdapter( adapt );
    }

    public void cleanText( View view )
    {
        actvSearch.setText( "" );
        view.setVisibility( View.INVISIBLE );
    }

    private List<View> generateFixTabs()
    {
        List<View> list = new ArrayList<View>();
        View homePage = createIndicatorViewLayer1( R.drawable.icon_home, "首页" );
        //        homePage.setBackgroundResource( R.drawable.navi_bar_selected );
        list.add( homePage );
        list.add( createIndicatorViewLayer1( R.drawable.icon_heart, "热门推荐" ) );
        list.add( createIndicatorViewLayer1( R.drawable.icon_search, "查找商户" ) );
        list.add( createIndicatorViewLayer1( R.drawable.icon_shake, "摇一摇" ) );
        list.add( createIndicatorViewLayer1( R.drawable.icon_vendor, "全部商户" ) );

        return list;
    }

    private List<View> generateDynamicTabs()
    {
        List<View> list = new ArrayList<View>();

        ResourceDataParser parser = new ResourceDataParser( Constant.RESOURCE );
        for( Map.Entry<Item, Map<Integer, Item>> entry : parser.category.entrySet() )
        {
            Item item = entry.getKey();
            String itemName = item.name;
            int itemId = item.id;
            Log.d( "MainActivity", "item name: " + itemName + ", item id: " + itemId );

            if( itemId != 0 )
            {
                cateIdList.add( itemId );
                list.add( createIndicatorViewLayer2( itemName ) );
            }
        }

        // check whether use has logged in
        //        SharedPreferences sharedPref = getSharedPreferences( "userInfo", Context.MODE_PRIVATE );
        //        //        TabSpec tabSpec = null;
        //        if( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN, false )
        //            || ( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_CHECKED, false ) && !sharedPref
        //                .getBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false ) ) )
        //        {
        //            //            tabSpec = tabHost.newTabSpec( TAG_USER_INFO ).setIndicator( createIndicatorViewLoginUserInfo() )
        //            //                .setContent( new Intent( this, MemberCenterActivity.class ) );
        //            list.add( createIndicatorViewLoginUserInfo() );
        //        }
        //        else
        //        {
        //            //            tabSpec = tabHost.newTabSpec( TAG_USER_INFO ).setIndicator( createIndicatorViewLogoutUserInfo() )
        //            //                .setContent( new Intent( this, LoginActivity.class ) );
        //            list.add( createIndicatorViewLogoutUserInfo() );
        //        }
        //        tabSpecList.add( tabSpec );

        // these tab doesn't have tab indicator
        //        tabSpecList.add( tabHost.newTabSpec( "11" ).setIndicator( creatNullView() )
        //            .setContent( new Intent( this, FindResultActivity.class ) ) );
        return list;
    }

    //    private void generateTabsOnResource()
    //    {
    //
    //        ResourceDataParser parser = new ResourceDataParser( Constant.RESOURCE );
    //        for( Map.Entry<Item, Map<Integer, Item>> entry : parser.category.entrySet() )
    //        {
    //            Item item = entry.getKey();
    //            String itemName = item.name;
    //            int itemId = item.id;
    //            Log.d( "MainActivity", "item name: " + itemName + ", item id: " + itemId );
    //
    //            if( itemId == 0 )
    //            {
    //                tabSpecList.add( tabHost.newTabSpec( "0" )
    //                    .setIndicator( createIndicatorViewLayer1( R.drawable.icon_vendor_press, "全部商户" ) )
    //                    .setContent( newVendorListIntent( 0, 0 ).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) ) );
    //            }
    //            else
    //            {
    //                tabSpecList.add( tabHost.newTabSpec( "" + itemId ).setIndicator( createIndicatorViewLayer2( itemName ) )
    //                    .setContent( newVendorListIntent( itemId, 0 ).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) ) );
    //            }
    //        }

    //        tabSpecList.add( tabHost.newTabSpec( "6" ).setIndicator( createIndicatorViewLayer2( "餐饮美食" ) )
    //            .setContent( newVendorListIntent( 1, 0 ) ) );
    //        tabSpecList.add( tabHost.newTabSpec( "7" ).setIndicator( createIndicatorViewLayer2( "休闲娱乐" ) )
    //            .setContent( newVendorListIntent( 2, 0 ) ) );
    //        tabSpecList.add( tabHost.newTabSpec( "8" ).setIndicator( createIndicatorViewLayer2( "生活服务" ) )
    //            .setContent( newVendorListIntent( 4, 0 ) ) );
    //        tabSpecList.add( tabHost.newTabSpec( "9" ).setIndicator( createIndicatorViewLayer2( "酒店旅游" ) )
    //            .setContent( newVendorListIntent( 5, 0 ) ) );
    //        tabSpecList.add( tabHost.newTabSpec( "10" ).setIndicator( createIndicatorViewLayer2( "商场超市" ) )
    //            .setContent( newVendorListIntent( 3, 0 ) ) );
    //    }

    private Intent newVendorListIntent( int pareCate, int subCate )
    {
        Intent intent = new Intent( this, VendorListActivity.class );
        intent.putExtra( Constant.EXTRA_INT_CRITERIA_PARE_CATE, pareCate );
        intent.putExtra( Constant.EXTRA_INT_CRITERIA_SUB_CATE, subCate );
        intent.putExtra( Constant.EXTRA_INT_CRITERIA_CANTON, 0 );
        intent.putExtra( Constant.EXTRA_INT_CRITERIA_BUSI_CIRC, 0 );

        return intent;
    }

    private View createIndicatorViewLayer1( int resId, String title )
    {
        //        LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        //        View tabIndicator = inflater.inflate( R.layout.navi_tab_ind_layer_1, null, false );
        View tabIndicator = LayoutInflater.from( this ).inflate( R.layout.navi_tab_ind_layer_1, null );
        TextView titleView = (TextView) tabIndicator.findViewById( R.id.navi_bar_ind_title );
        titleView.setText( title );
        ImageView iv = (ImageView) tabIndicator.findViewById( R.id.navi_tab_ind_layer_1_iv );
        iv.setImageResource( resId );

        //        tabIndicator.setOnTouchListener( new OnTouchListener()
        //        {
        //
        //            @Override
        //            public boolean onTouch( View v, MotionEvent event )
        //            {
        //                //                dynAdapter.select( -1 );
        //                //                fixAdapter.select( -1 );
        //                if( MotionEvent.ACTION_DOWN == event.getAction() )
        //                {
        //                    if( selectedItem != null ) // when touch down, last selected item should be still selected 
        //                    {
        //                        selectedItem.setSelected( true );
        //                    }
        //                }
        //                //                        else if( MotionEvent.ACTION_MOVE == event.getAction() )
        //                //                        {
        //                //                            v.setBackgroundColor( getResources().getColor( R.color.navi_1 ) );
        //                //                        }
        //                return false;
        //            }
        //        } );
        return tabIndicator;
    }

    private View createIndicatorViewLayer2( String title )
    {
        //        LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        //        View tabIndicator = inflater.inflate( R.layout.navi_tab_ind_layer_2, null, false );
        View tabIndicator = LayoutInflater.from( this ).inflate( R.layout.navi_tab_ind_layer_2, null );
        final TextView titleView = (TextView) tabIndicator.findViewById( R.id.navi_bar_ind_title );
        titleView.setText( title );

        //        tabIndicator.setOnTouchListener( new OnTouchListener()
        //        {
        //
        //            @Override
        //            public boolean onTouch( View v, MotionEvent event )
        //            {
        //                //                dynAdapter.select( -1 );
        //                //                fixAdapter.select( -1 );
        //                if( MotionEvent.ACTION_DOWN == event.getAction() )
        //                {
        //                    titleView.setBackgroundColor( Color.parseColor( "#64584c" ) );
        //                }
        //                else if( MotionEvent.ACTION_MOVE == event.getAction() )
        //                {
        //                    titleView.setBackgroundColor( getResources().getColor( R.color.navi_2 ) );
        //                }
        //                return false;
        //            }
        //        } );

        return tabIndicator;
    }

    public void toSettingPage( View view )
    {
        handleNaviBar();
        Intent intent = new Intent( this, SettingActivity.class );
        startActivity( intent );
    }

    public void updateUserInfo()
    {

        TextView tvUserInfo = (TextView) findViewById( R.id.navi_tab_ind_login_tv_account_info );

        if( sharedPref.getBoolean( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN, false ) )
        {
            String userName = sharedPref.getString( MemberCenterActivity.SHARED_PREF_STR_ACCOUNT_NAME, "" );
            String userCredit = sharedPref.getString( MemberCenterActivity.SHARED_PREF_STR_USER_CREDIT, "" );
            tvUserInfo.setText( userName + "  积分:" + userCredit );
            llLogin.setOnClickListener( new OnClickToMemberCenterPage() );
        }
        else
        {
            tvUserInfo.setText( "请登录" );
            llLogin.setOnClickListener( new OnClickToLoginPage() );
        }
    }

    public void handleNaviBar()
    {
        if( ignoreNaviBar )
        {
            ignoreNaviBar = false;
            return;
        }

        if( isNaviBarShown )
        {
            slideToLeft( widthOfNaviBar );
        }
        else
        {
            slideToRight( 0 );
        }
        //        isNaviBarShown = !isNaviBarShown;
    }

    /**
     * 
     * @param x
     *            tab content's x position
     */
    private void slideToLeft( final int x )
    {
        new Thread()
        {
            public void run()
            {
                int times = x / SLIDE_SPEED;
                for( int i = x, m = 0; m < times + 1; m++ )
                {
                    i -= SLIDE_SPEED;
                    Message msg = updateHandler.obtainMessage();
                    if( i < 0 )
                        i = 0;
                    msg.arg1 = i;
                    updateHandler.sendMessage( msg );
                    try
                    {
                        Thread.sleep( 20 );
                    }
                    catch( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
                }
                isNaviBarShown = false;

            }
        }.start();
    }

    /**
     * 
     * @param x
     *            tab content's x position
     */
    private void slideToRight( final int x )
    {
        new Thread()
        {
            public void run()
            {
                int times = ( widthOfNaviBar - x ) / SLIDE_SPEED;
                for( int i = x, m = 0; m < times + 1; m++ )
                {
                    i += SLIDE_SPEED;
                    Message msg = updateHandler.obtainMessage();
                    if( i > widthOfNaviBar )
                        i = widthOfNaviBar;
                    msg.arg1 = i;
                    updateHandler.sendMessage( msg );
                    try
                    {
                        Thread.sleep( 30 );
                    }
                    catch( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
                }
                isNaviBarShown = true;
            }
        }.start();
    }

    Handler updateHandler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {

            if( msg.arg1 == 0 )
            {
                isItemClickable = true;
                enableNaviBar( false );
                clickArea.setVisibility( View.GONE );
            }
            else
            {
                enableNaviBar( true );

            }

            android.view.ViewGroup.LayoutParams param = new AbsoluteLayout.LayoutParams(
                AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, msg.arg1, 0 );

            if( msg.arg1 == widthOfNaviBar )
            {
                clickArea.setVisibility( View.VISIBLE );
                clickArea.setLayoutParams( param );
            }

            //            tabContent.setLayoutParams( param );
            llContainer.setLayoutParams( param );

        }

    };

    private void enableNaviBar( boolean bool )
    {

        int visibility = 0;
        if( bool )
        {
            visibility = View.VISIBLE;
        }
        else
        {
            visibility = View.INVISIBLE;
        }

        //        tabHost.getTabWidget().setVisibility( visibility );
        gvTabs.setVisibility( visibility );

        actvSearch.setVisibility( visibility );

        btnSetting.setVisibility( visibility );
    }

    public void hideMenu( View view )
    {
        handleNaviBar();
    }

    public class DynamicTabAdapter
        extends BaseAdapter
    {
        List<View> list;

        public DynamicTabAdapter(List<View> list)
        {
            this.list = list;
        }

        public int getCount()
        {
            return list.size();
        }

        public Object getItem( int position )
        {
            return position;
        }

        public long getItemId( int position )
        {
            return position;
        }

        /**
         * 设置选中的效果
         */
        public void select( int index )
        {
            int n = list.size();
            if( n > 0 )
            {
                for( int i = 0; i < list.size(); i++ )
                {
                    if( index == -1 || i != index )
                    {
                        list.get( i ).setSelected( false );
                        list.get( i ).findViewById( R.id.navi_bar_ind_title )
                            .setBackgroundResource( R.drawable.color_tab_ind_layer2 );
                    }
                }
            }
            if( index != -1 )
            {
                list.get( index ).setSelected( true );
                list.get( index ).findViewById( R.id.navi_bar_ind_title )
                    .setBackgroundResource( R.color.navi_2_selected );//设置选中的样式
            }
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            return list.get( position );
        }
    }

    public class FixTabAdapter
        extends BaseAdapter
    {
        List<View> list;

        public FixTabAdapter(List<View> list)
        {
            this.list = list;
        }

        public int getCount()
        {
            return list.size();
        }

        public Object getItem( int position )
        {
            return position;
        }

        public long getItemId( int position )
        {
            return position;
        }

        public void select( int index )
        {
            int n = list.size();
            if( n > 0 )
            {
                for( int i = 0; i < list.size(); i++ )
                {
                    if( index == -1 || i != index )
                    {
                        list.get( i ).setSelected( false );
                        setImageRes( i );
                        list.get( i ).setBackgroundResource( R.drawable.color_tab_ind_layer1 );
                    }
                }
                if( index != -1 )
                {
                    list.get( index ).setSelected( true );
                    setImageResPressed( index );
                    list.get( index ).setBackgroundResource( R.drawable.navi_bar_selected );
                }
            }

        }

        private void setImageRes( int i )
        {
            int resId = 0;

            switch( i )
            {
                case 0:
                    resId = R.drawable.icon_home;
                    break;
                case 1:
                    resId = R.drawable.icon_heart;
                    break;
                case 2:
                    resId = R.drawable.icon_search;
                    break;
                case 3:
                    resId = R.drawable.icon_shake;
                    break;
                case 4:
                    resId = R.drawable.icon_vendor;
                    break;

                default:
                    break;

            }
            ( (ImageView) list.get( i ).findViewById( R.id.navi_tab_ind_layer_1_iv ) ).setImageResource( resId );
        }

        private void setImageResPressed( int i )
        {
            int resId = 0;

            switch( i )
            {
                case 0:
                    resId = R.drawable.icon_home_pressed;
                    break;
                case 1:
                    resId = R.drawable.icon_heart_pressed;
                    break;
                case 2:
                    resId = R.drawable.icon_search_pressed;
                    break;
                case 3:
                    resId = R.drawable.icon_shake_pressed;
                    break;
                case 4:
                    resId = R.drawable.icon_vendor_pressed;
                    break;
                default:
                    resId = R.drawable.icon_home_pressed;
                    break;

            }
            ( (ImageView) list.get( i ).findViewById( R.id.navi_tab_ind_layer_1_iv ) ).setImageResource( resId );
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            return list.get( position );
        }

    }

    class MyTimer
        extends CountDownTimer
    {
        public MyTimer(long millisInFuture, long countDownInterval)
        {
            super( millisInFuture, countDownInterval );
        }

        @Override
        public void onTick( long millisUntilFinished )
        {
        }

        @Override
        public void onFinish()
        {
            timeOfPressExit = 0;
        }
    }

    private boolean isHomePage = true;
    private int timeOfPressExit = 0;

    private MyTimer timer = new MyTimer( 2000, 1000 );

    @Override
    public void onBackPressed()
    {
        if( isHomePage )
        {
            timeOfPressExit++;
            if( timeOfPressExit >= 2 )
            {
                timer.cancel();
                super.onBackPressed();
                SplashActivity.MAIN_IS_IN_STACK = false;
            }
            else
            {
                Toast.makeText( this, "再次按下将会退出程序", Toast.LENGTH_SHORT ).show();
                timer.start();
            }
        }
        else
        {
            if( needsOwnBack )
            {
                getLocalActivityManager().getCurrentActivity().onBackPressed();
            }
            else
            {
                ignoreNaviBar = true;
                switchActivityForFixTabs( 0 );
            }
        }
        if( isNaviBarShown )
        {
            handleNaviBar();
        }
    }

    @Override
    public boolean onTouch( View v, MotionEvent event )
    {

        // 松开的时候要判断，如果不到半屏幕位子则缩回去，  
        if( MotionEvent.ACTION_UP == event.getAction() && isScrolling == true )
        {
            AbsoluteLayout.LayoutParams originalParams = ( (AbsoluteLayout.LayoutParams) llContainer.getLayoutParams() );
            // 缩回去  
            if( originalParams.x < widthOfNaviBar / 2 )
            {
                slideToLeft( originalParams.x );
            }
            else
            {
                slideToRight( originalParams.x );
            }
        }

        return mGestureDetector.onTouchEvent( event );
    }

    @Override
    public boolean onDown( MotionEvent e )
    {
        mScrollX = 0;
        isScrolling = false;
        // 将之改为true，不然事件不会向下传递.  
        return true;
    }

    @Override
    public void onShowPress( MotionEvent e )
    {
    }

    @Override
    public boolean onSingleTapUp( MotionEvent e )
    {
        hideMenu( null );
        return true;
    }

    @Override
    public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY )
    {
        isScrolling = true;
        mScrollX += distanceX;// distanceX:向左为正，右为负  
        AbsoluteLayout.LayoutParams layoutParams = (AbsoluteLayout.LayoutParams) llContainer.getLayoutParams();
        int x = (int) ( layoutParams.x - mScrollX );
        layoutParams.x = x;

        if( layoutParams.x < 0 )
        {
            isScrolling = false;// 拖过头了不需要再执行AsynMove了
            isNaviBarShown = false;
            layoutParams.x = 0;

        }
        else if( layoutParams.x > widthOfNaviBar )
        {
            // 拖过头了不需要再执行AsynMove了  
            isScrolling = false;
            isNaviBarShown = true;
            layoutParams.x = widthOfNaviBar;
        }
        llContainer.setLayoutParams( layoutParams );
        clickArea.setLayoutParams( layoutParams );
        return true;
    }

    @Override
    public void onLongPress( MotionEvent e )
    {

    }

    @Override
    public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
    {
        return false;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        BMapManager mBMapMan = ( (MyApplication) getApplication() ).getBMapMan();
        if( mBMapMan != null )
        {
            mBMapMan.destroy();
        }
    }

}
